package com.anan.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author: Painter
 * @project_name: onlyoffice
 * @system_login: sunshine
 * @time: 2023/10/910:40
 */

@Controller
@RequestMapping("/office")
public class EditController {


    @RequestMapping("/online/{id}")
    public void online(HttpServletResponse response, HttpServletRequest request,@PathVariable("id") Integer id) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");

            String[] type = {"0","docx","xlsx","pdf","pptx"};

            // 读文件输入流
            String filePath = "C:\\Users\\23287\\Desktop\\java\\onlyoffice\\file\\onlyoffice."+type[id];
            InputStream fileInputStream = new FileInputStream(filePath);
//            StreamUtils.copy(fileInputStream, response.getOutputStream());
            OutputStream out = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(bytes)) !=-1){
                out.write(bytes, 0, len);
            }
            out.close();
            fileInputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping( "/save/{id}")
    public void save(HttpServletResponse response, HttpServletRequest request,@PathVariable("id") Integer id) throws IOException {
        String[] type = {"0","docx","xlsx","pdf","pptx"};
        String filepath = "C:\\Users\\23287\\Desktop\\java\\onlyoffice\\file\\onlyoffice."+type[id];
        File file1 = new File(filepath);
        ServletInputStream inputStream1 = request.getInputStream();
        ;
//        byte[] bytes = new byte[inputStream1.available()];
//
//        int read = inputStream1.read(bytes);
//
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
//        fileOutputStream.write(bytes);
        StreamUtils.copy(request.getInputStream(), fileOutputStream);
        fileOutputStream.close();
        inputStream1.close();

    }


}
